import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

class WordpairPage extends StatefulWidget {
  WordpairPage({Key key, this.title}) : super(key: key);
  final String title;
  _WordpairPageState createState() => _WordpairPageState();
}

class _WordpairPageState extends State {
  final _biggerFont = new TextStyle(fontSize: 18.0);
  final _pairs = <WordPair>[];
  final _saved = new Set<WordPair>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("首页"),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.list),
            onPressed: _savedPush,
          )
        ],
      ),
      body: _buildListView(),
    );
  }

  Widget _buildListView() {
    return new ListView.builder(
      padding: new EdgeInsets.all(16.0),
      itemBuilder: (context, i) {
        if (i.isOdd) return new Divider();
        final index = i ~/ 2;
        if (_pairs.length <= index) {
          _pairs.addAll(generateWordPairs().take(10));
        }
        return _buildListRow(_pairs[index]);
      },
    );
  }

  Widget _buildListRow(WordPair pair) {
    final alreadSaved = _saved.contains(pair);
    return new ListTile(
      title: new Text(pair.asPascalCase, style: _biggerFont),
      trailing: new Icon(alreadSaved ? Icons.favorite : Icons.favorite_border, color: alreadSaved ? Colors.red : null),
      onTap: () {
        setState(() {
          if (alreadSaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }

  void _savedPush() {
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      final tiles = _saved.map((WordPair pair) {
        return new ListTile(
          title: new Text(pair.asPascalCase, style: _biggerFont),
          onTap: (){
          },);
      });

      final divider = ListTile.divideTiles(
        context: context, 
        tiles: tiles,
        ).toList();

      return new Scaffold(
        appBar: new AppBar(
          title: new Text("收藏"),
        ),
        body: new ListView(
          children: divider,
        ),
      );
    }));
  }
}
